from odoo import api, models, fields, _
from odoo.exceptions import ValidationError
from collections import defaultdict
from odoo.tools import float_compare
import json
from datetime import timedelta


class SubcontractingQtyWizard(models.TransientModel):
    _name = 'subcontracting.qty.wizard'

    order_id = fields.Many2one('purchase.order')
    is_all_outside = fields.Boolean(related='order_id.is_all_outside', help='包工包料/多工序外发')
    line_ids = fields.One2many('subcontracting.qty.line.wizard', 'wizard_id')
    subcon_outside_id = fields.Many2one('stock.subcon.outside')

    def button_confirm(self):
        self = self.sudo()
        wo_defaultdict = defaultdict(list)
        for line in self.line_ids:
            purchase_line = line.purchase_order_line_id
            wo = line.purchase_order_line_id.workorder_id
            if (line.product_qty - line.scrap_panel_qty) < line.qty_received:
                raise ValidationError('最大可接收数量不能超过【{}】.'.format(line.product_qty - line.scrap_panel_qty))

            # 回写到工单上是pnl
            line.purchase_order_line_id.qty_received = line.qty_received
            # 回写到工序上pce
            pcs_qty_received = line.qty_received * wo.value_pnl
            sub_received_qty = wo.subcontracting_received_qty
            sub_received_pnl_qty = wo.subcontracting_received_pnl_qty
            sub_received_qty += pcs_qty_received
            sub_received_pnl_qty += line.qty_received
            # 将接收数量回写到工序上，方便过数的时候使用
            wo.subcontracting_received_qty = sub_received_qty
            wo.subcontracting_received_pnl_qty = sub_received_pnl_qty
            # note_sb = wo.note_sb if wo.note_sb else ''
            json_str = json.dumps({'datetime': fields.Datetime.to_string(fields.Datetime.now() + timedelta(hours=7)),
                                   'pcs': pcs_qty_received,
                                   'panel': line.qty_received,
                                   'purchase': line.purchase_order_line_id.order_id.name})
            note_sb = wo.note_sb + ' - ' + json_str if wo.note_sb else json_str
            # 获取工单
            wo_defaultdict[purchase_line.s_production_id].append(line)
            wo.note_sb = note_sb
            # wo.note_sb = note_sb + '\n' +  '采购订单{}-->接收数量 PCS: {}  PANEL: {}\n'.format(line.purchase_order_line_id.order_id.name,
            #                                                                  pcs_qty_received, sub_received_pnl_qty)

            line.subcon_line_id.sub_receipt_qty += line.qty_received
        # quality_team_id = self.env.ref('pcbmanufact.quality_alert_subcon').id
        # # 接收数量进行检查, 如不相等, 需做另外处理, 创建报损单
        # for s_production_id, lines in wo_defaultdict.items():
        #     subcon_ids = []
        #     for line in lines:
        #         subcon_ids.append((0, 0, {
        #             'subcon_line_id': line.subcon_line_id.id,
        #             'product_qty': line.product_qty,
        #             'qty_received': line.qty_received,
        #         }))
        #     alert = self.env['quality.alert'].sudo().search([('s_production_id', '=', s_production_id.id)], limit=1)
        #     if not alert:
        #         workorder_ids = s_production_id.workorder_ids.filtered(lambda x: x.qty_wip > 0)
        #         if not workorder_ids:
        #             self.order_id.subcon_in = True
        #             self.order_id.subcon_in_date = fields.Datetime.now()
        #             # raise ValidationError(_('Production order without online quantity'))
        #             return {
        #                 'warning': {
        #                     'title': _('Warning'),
        #                     'message': _('Production order without online quantity')
        #                 }
        #             }
        #         alert.create({
        #             'team_id': quality_team_id,
        #             's_production_id': s_production_id.id,
        #             's_workorder_id': workorder_ids[0].id,
        #             'product_id': s_production_id.product_id.id,
        #             'product_tmpl_id': s_production_id.product_id.product_tmpl_id.id,
        #             's_work_station_id': workorder_ids[0].workcenter_id.work_station_id.id,
        #             'workcenter_id': workorder_ids[0].workcenter_id.id,
        #             's_qty_wip': workorder_ids[0].qty_wip,
        #             's_qty_wip_set': workorder_ids[0].qty_wip_set,
        #             's_qty_wip_pnl': workorder_ids[0].qty_wip_pnl,
        #             'subcon_ids': subcon_ids,
        #         })
        #     else:  # 加入新的
        #         alert.write({
        #             'subcon_ids': subcon_ids
        #         })
        self.order_id.subcon_in = True
        self.order_id.subcon_in_date = fields.Datetime.now()

    def button_confirm02(self):
        """多工序接收
        1、判断结束工序
        2、开始许工需要回写接收数量
        3、开始到结束工序(不包含结束工序)自动完成
        4、质检,,,,
        """
        self = self.sudo()
        # wo_defaultdict = defaultdict(list)
        for line in self.line_ids:
            purchase_line = line.purchase_order_line_id
            if line.product_qty < line.qty_received:
                raise ValidationError('最大可接收数量不能超过【{}】.'.format(line.product_qty))
            # 回写到工单上是pnl
            line.purchase_order_line_id.qty_received = line.qty_received
            # 回写到工序上pce
            line.purchase_order_line_id.qty_received = line.qty_received
            # 回写到工序上pce
            for wo in line.workorder_ids:
                pcs_qty_received = line.qty_received * wo.value_pnl
                sub_received_qty = wo.subcontracting_received_qty
                sub_received_pnl_qty = wo.subcontracting_received_pnl_qty
                sub_received_qty += pcs_qty_received
                sub_received_pnl_qty += line.qty_received
                json_str = json.dumps({'datetime': fields.Datetime.to_string(fields.Datetime.now() + timedelta(hours=7)),
                            'pcs': pcs_qty_received,
                            'panel': line.qty_received,
                            'purchase': line.purchase_order_line_id.order_id.name})
                note_sb = wo.note_sb + ' - ' + json_str if wo.note_sb else json_str
                wo.update({
                    'subcontracting_received_qty': sub_received_qty,
                    'subcontracting_received_pnl_qty': sub_received_pnl_qty,
                    'pol_ids': [(4, purchase_line.id)],
                    'note_sb': note_sb
                })
                # wo.update({
                #     'subcontracting_received_qty': sub_received_qty,
                #     'subcontracting_received_pnl_qty': sub_received_pnl_qty,
                #     # 'is_subcontracting': True,
                #     'pol_ids': [(4, purchase_line.id)],
                #     'note_sb': note_sb + '-' + '采购订单{}-->接收数量 PCS: {}  PANEL: {}\n'.format(
                #         line.purchase_order_line_id.order_id.name,
                #         pcs_qty_received, line.qty_received)
                # })
            line.subcon_line_id.sub_receipt_qty += line.qty_received
            # wo_defaultdict[purchase_line.s_production_id].append(line)
        # quality_team_id = self.env.ref('pcbmanufact.quality_alert_subcon').id
        # # 接收数量进行检查, 如不相等, 需做另外处理, 创建报损单
        # for s_production_id, lines in wo_defaultdict.items():
        #     subcon_ids = []
        #     for line in lines:
        #         subcon_ids.append((0, 0, {
        #             'subcon_line_id': line.subcon_line_id.id,
        #             'product_qty': line.product_qty,
        #             'qty_received': line.qty_received,
        #         }))
        #     alert = self.env['quality.alert'].sudo().search([('s_production_id', '=', s_production_id.id)], limit=1)
        #     if not alert:
        #         workorder_ids = s_production_id.workorder_ids.filtered(lambda x: x.qty_wip > 0)
        #         if not workorder_ids:
        #             self.order_id.subcon_in = True
        #             self.order_id.subcon_in_date = fields.Datetime.now()
        #             # raise ValidationError(_('Production order without online quantity'))
        #             return {
        #                 'warning': {
        #                     'title': _('Warning'),
        #                     'message': _('Production order without online quantity')
        #                 }
        #             }
        #         alert.create({
        #             'team_id': quality_team_id,
        #             's_production_id': s_production_id.id,
        #             's_workorder_id': workorder_ids[0].id,
        #             'product_id': s_production_id.product_id.id,
        #             'product_tmpl_id': s_production_id.product_id.product_tmpl_id.id,
        #             's_work_station_id': workorder_ids[0].workcenter_id.work_station_id.id,
        #             'workcenter_id': workorder_ids[0].workcenter_id.id,
        #             's_qty_wip': workorder_ids[0].qty_wip,
        #             's_qty_wip_set': workorder_ids[0].qty_wip_set,
        #             's_qty_wip_pnl': workorder_ids[0].qty_wip_pnl,
        #             'subcon_ids': subcon_ids,
        #         })
        #     else:  # 加入新的
        #         alert.write({
        #             'subcon_ids': subcon_ids
        #         })
        self.order_id.subcon_in = True
        self.order_id.subcon_in_date = fields.Datetime.now()


class SubcontractingLineQtyWizard(models.TransientModel):
    _name = 'subcontracting.qty.line.wizard'

    def _compute_scrap_panel_qty(self):
        for rec in self:
            if rec.wizard_id.is_all_outside:
                wo = rec.subcon_line_id.start_workorder_id
            else:
                wo = rec.purchase_order_line_id.workorder_id
            rec.scrap_panel_qty = sum(wo.s_scrap_ids.mapped('scrap_panel_qty'))

    wizard_id = fields.Many2one('subcontracting.qty.wizard')
    subcon_line_id = fields.Many2one('stock.subcon.outside.line')
    purchase_order_line_id = fields.Many2one('purchase.order.line')
    service_product_id = fields.Many2one('product.product', string='Service Product')
    product_qty = fields.Float(string='Qty Product')
    qty_received = fields.Float(string='Qty Received')
    workorder_ids = fields.Many2many('mrp.workorder', string='可选工序')
    done_workorder_id = fields.Many2one('mrp.workorder', string='完成到工序')
    scrap_panel_qty = fields.Float(string='工序已报废数量', compute="_compute_scrap_panel_qty")
    s_production_id = fields.Many2one('mrp.production', string='工单', related='purchase_order_line_id.s_production_id',copy=False, readonly=True)
